package com.example.repository.write;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.repository.write.mappers", sqlSessionTemplateRef  = "helloSeconddb")
public class DataSourceWriteConfig
{//用Qualifier内部方法名不能跟ReadConfig一样  一样会报错
    @Bean(name="hello2db")
    @ConfigurationProperties(prefix = "spring.hello2-db")
    public DataSource _dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name="hello22db")
    public SqlSessionFactory _sqlSessionFactory(@Qualifier("hello2db")DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:write-mybatis-config.xml"));
        return bean.getObject();
    }

    @Bean(name = "hello22tm")
    public DataSourceTransactionManager _testTransactionManager(@Qualifier("hello2db") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "helloSeconddb")
    public SqlSessionTemplate _sqlSessionTemplate(@Qualifier("hello22db") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
